function [data_avg,t_avg] = osl_movavg(data,t,winsize,overlap,varargin)

% Moving window averaging
% [data_avg,t_avg] = ABMOVAVG(data,t,winsize,overlap)
% -----------------------------------------------------------------
% data        - data to average
% t           - vector of sample times
% winsize     - window to average over (samples)
% overlap     - amount of segment overlapping (e.g. 0.75 = 75% overlap).
%               Default = 0.75.
% varargin    - catch use of deprecated Hanning flag
% -----------------------------------------------------------------
% AB 2011
 
if nargin < 4;    overlap     = 0.75;        end

% NOTE: Hanning window functionality has been removed as can introduce edge
% effects.

data = [nan(1,winsize),data,nan(1,winsize)];
t    = [nan(1,winsize),t,nan(1,winsize)];

bf       = buffer(data,winsize,round(winsize*overlap),'nodelay');
tbf      = buffer(t,winsize,round(winsize*overlap),'nodelay');

% reject data sections where more than 25% of data is NaN
nans = sum(isnan(bf)) > 0.25*winsize;
bf( :,nans) = nan; % - do this by replacing all with nans
tbf(:,nans) = nan; % - do this by replacing all with nans

data_avg = nanmean(bf);
t_avg    = nanmean(tbf);   

data_avg(t_avg==0) = [];
   t_avg(t_avg==0) = [];
   
 data_avg(isnan(t_avg)) = [];
    t_avg(isnan(t_avg)) = [];  
   
end
  
